<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" >
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">
              状态：
              <a-tag color="#87d068">{{ data.form.docStatus }}</a-tag>
            </h3>
            <h3 style="display: inline">
              审核：
              <a-tag color="#87d068">{{ data.form.approved ? '已审核' : '未审核' }}</a-tag>
            </h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()"> 返 回</a-button>

              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || !data.form.edit)"> 保 存</a-button>
              <a-button @click="edit()" v-if="!(data.form.edit || data.form.docStatus === 'L' || data.form.edit)"> 编 辑</a-button>
              <a-button @click="del()" v-if="!(data.form.edit || data.form.docStatus === 'L')"> 删 除</a-button>
              <a-button @click="approved()" v-if="!data.form.edit" value="6"> 审 核</a-button>
              <a-dropdown>
                <a-button >更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" :disabled="!(data.form.docStatus !== 'C')">关闭</a-menu-item>
                    <a-menu-item key="b" :disabled="!(data.form.docStatus === 'C')">打开</a-menu-item>
                    <a-menu-item key="c" :disabled="data.form.approved">查看审核</a-menu-item>
                    <a-menu-item key="d" :disabled="!data.form.approved">取消审核</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="模板名称">
              <a-input v-if="data.form.edit" v-model:value="data.form.docName"></a-input>
              <span v-else>{{ data.form.docName }}</span>
            </a-form-item>
            <a-form-item label="表编码">
              <a-select v-if="data.form.edit" v-model:value="data.form.tabName">
                <a-select-option v-for="item in data.tableList" :key="item.tableName" :value="item.tableName"
                  >{{ item.tableName + '&nbsp;&nbsp;' + item.tableComment }}
                </a-select-option>
              </a-select>
              <span v-else>{{ data.form.tabName }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="细表">

                <a-button @click="lineaAdd" type="link">
                  <template #icon>
                    <ExportOutlined />
                  </template>
                  插入行
                </a-button>


            <a-table
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
              size="small"
              :dataSource="data.form.lista"
              :columns="columnsa"
              rowKey="lineNum"
              :scroll="{ x: 1500 }"
            >
              <template #bodyCell="{ text, record, column }">
                <template v-if="record.edit && column.dataIndex === 'phaseName'">
                  <a-input v-model:value="record.phaseName"></a-input>
                </template>

                <template v-if="column.dataIndex === 'action'">
                  <a-button v-if="data.form.edit" @click="lineaDel(record)" type="link" danger>
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>

  <userList :visible="data.visible.user" :onClose="onLineaColse"></userList>
</template>
<script setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';

  import { apptemordApi } from '/src/api/business/erp/apptemord-api';

  import { smartSentry } from '/src/lib/smart-sentry';
  import _ from 'lodash';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
  import macList from '/src/components/business/erp/macList.vue';
  import userList from '/src/components/business/erp/userList.vue';

  import { codeGeneratorApi } from '/src/api/support/code-generator-api';

  // ---------------------------- 表格列 ----------------------------
  const route = useRoute();
  const router = useRouter();
  const departmentTreeSelect = ref();
  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    categoryId: undefined,
    searchWord: '',
    goodsStatus: undefined,
    place: undefined,
    shelvesFlag: undefined,
    goodsType: undefined,
    pageNum: 1,
    pageSize: 100,
    sortItemList: [],
  };

  // 查询表单form
  const queryForm = reactive(_.cloneDeep(queryFormState));
  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      objName: '测试单据',
      absId: '',
      approved: false,
      docStatus: 'O',
      macName: '测试设备',
      docName: '',
      createById: 0,
      createBy: '',
      createTime: '',
      updateById: 0,
      updateBy: '',
      updateTime: '',
      edit: false,
      lista: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      batchId: [{ required: true, message: '请输入设备名称' }],
      itemName: [{ required: true, message: '请输入设备地址' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    activeKey: '1',
    visible: {
      mac: false,
      user: false,
    },
    tableList: [],
  });

  const columnsa = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
      width: 100,
    },
    {
      title: '员工编码',
      dataIndex: 'userId',
      align: 'center',
      width: 100,
    },
    {
      title: '员工名称',
      dataIndex: 'userName',
      align: 'center',
      width: 100,
    },

    {
      title: '阶段名称',
      dataIndex: 'phaseName',
      align: 'center',
      width: 100,
    },

    {
      title: '行状态',
      dataIndex: 'lineStatus',
      align: 'center',
      width: 100,
    },

    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      align: 'center',
    },
  ]);
  const tableLoading = ref(false);
  const formRef = ref(null);

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    try {
      let queryResult = await apptemordApi.info(data.form.docEntry);
      data.form = queryResult.data;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  onMounted(init);

  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  function back() {
    router.push({ path: '/erp/apptemord' });
  }

  function add() {
    data.form.createById = 0;
    data.form.createBy = '';
    data.form.createTime = '';
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/apptemorda', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          apptemordApi.update(data.form).then((res) => {
            queryData(data.form.docEntry);
            message.success('修改成功！');
          });
        } else {
          apptemordApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/erp/apptemorda', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        apptemordApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/erp/apptemord' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  function approved() {}

  function more({ key }) {}

  function refresh() {
    queryData();
    message.success('刷新成功！');
  }

  // ---------------------------------------M---------------------------------------------

  function codeGenerator() {
    codeGeneratorApi.queryTableList(queryForm).then((res) => {
      data.tableList = res.data.list;
    });
  }

  codeGenerator();

  // -------------------------------------a----------------------------------------------

  function onLineaColse(item) {
    data.visible.user = false;
    item.forEach((item) => {
      data.form.lista.push({
        docEntry: data.form.docEntry,
        lineNum: data.form.lista.length + 1,
        userId: item.employeeId,
        userName: item.actualName,
        approved: false,
        lineStatus: 'O',

        edit: true,
      });
    });
  }

  function lineaEdit(key) {
    key.edit = true;
  }

  function lineaAdd() {
    data.visible.user = true;
  }

  function lineaDel(item) {
    data.form.lista.splice(item.lineNum - 1, 1);
    for (let i = item.lineNum - 1; i < data.form.lista.length; i++) {
      data.form.lista[i].lineNum = data.form.lista[i].lineNum - 1;
    }
  }
</script>
